package com.lsk.pc;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.mobile.MobileServices;
import com.lsk.util.*;
import org.apache.commons.lang.StringUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class PcService {
    Cache cache = Redis.use();

    MobileServices mobileServices=new MobileServices();
    /**
     * 注册   userCode和password
     *
     * @param map
     * @return
     */
    public ReturnData register(Map<String, String[]> map) {
        ReturnData rd = new ReturnData();//返回数据类型
        final String userCode = map.get("userCode")[0];
        final String password = map.get("password")[0];
        final String phone = map.get("phone")[0];
        String invitationNum[]=map.get("invitationNum");
        String veri = map.get("veri")[0];
        final String salt = UuidUtil.get6UUID();  //盐值
        final String userId = UuidUtil.get32UUID(); //随机生成的用户Id
        final String encodePassword = MD5.md5(password + salt); //password+salt 使用md加密后


        Object sysVeri = cache.get("register" + veri);//获取redis中的验证码
        if (sysVeri == null) {//验证码过期
            rd.setMsg("请重新获取验证码");
            rd.setCode("111111");
            rd.setResult(false);

        } else if (!(sysVeri+"").equals(veri)) {//验证码不正确
            rd.setMsg("验证码错误");
            rd.setCode("111111");
            rd.setResult(false);

        } else if ((sysVeri+"").equals(veri)) {//验证码正确
            //判断userCode与手机号是否唯一
            int flag = Db.queryInt("SELECT count(*) FROM sys_user WHERE 1=1  and ( userCode = '" + userCode + "'" + " or " + "phone='" + phone + "' )");


            if (flag != 0) {
                rd.setResult(false);
                rd.setCode("111111");
                rd.setMsg("账号已注册");

            } else {
                String parentId="";
                if (invitationNum!=null){
                    parentId = Db.queryStr("select id from yx_member where invitationNum='" + invitationNum[0] + "'");
                }
                String invNum=getInvitationNum();

                //开启事务
                final String finalParentId = parentId;
                final String finalInvNum = invNum;
                Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {
                        String userNameRandom = RadomUtil.getName();//生成一个随机名字
                        try {

                            Record userRecord=new Record().set("id", userId)
                                    .set("userName", userNameRandom)
                                    .set("userCode", userCode).set("password", encodePassword).set("salt", salt)
                                    .set("locked", 0).set("type", 2).set("phone", phone);

                            Db.save("sys_user", "id",userRecord

                            );

                            Db.save("yx_member", "id",new Record().set("id", UuidUtil.get32UUID())
                                    .set("name", userNameRandom).set("userId", userId).set("tel", phone).set("type",7)
                                    .set("parentId", finalParentId).set("invitationNum", finalInvNum)
                            );

                        } catch (Exception e) {

                            Syslog.error(e);
                            return false;//回滚
                        }
                        return true;

                    }
                });
                rd.setMsg("注册成功");
                rd.setCode("000000");
                rd.setResult(true);
            }
        }

        return rd;

    }
    /**
     * 登录
     *
     * @param map userCode和password
     * @return ReturnData
     */
    public ReturnData loginService(Map<String, String[]> map) {

        String[] phone = map.get("phone");
        String[] userCode = map.get("userCode");
        String[] password = map.get("password");
        String verifiction[] = map.get("veri");//验证码
        String type = map.get("type")[0];     //用来判断是账号登录还是验证码登录
        ReturnData rd = new ReturnData();
        if ((type == "userCodeLogin" || "userCodeLogin".equalsIgnoreCase(type))) {//账号登录
            int flag = Db.queryInt("SELECT count(id) from sys_user where    userCode = '" + userCode[0] + "'");
            if (flag == 0) {
                rd.setResult(false);
                rd.setCode("111111");
                rd.setMsg("用户不存在");
            } else {
                Record sysUser = Db.findFirst("SELECT * FROM sys_user WHERE userCode= '" + userCode[0] + "'");
                String salt = sysUser.get("salt");
                String encodePassword = sysUser.get("password");
                String newEncodePassword = MD5.md5(password[0] + salt);
                if (newEncodePassword.equals(encodePassword)) {
                    rd.setCode("000000");
                    rd.setMsg("登录成功");
                    rd.setResult(true);

                    String userId = sysUser.getStr("id");

                    /*查询会员信息*/


                    Record memberInfo = mobileServices.getMemberByUserIdService(userId);

                    String token = AES.AESEncode(userId);

                    Map<String, Record> userMap = new HashMap<>();
                    userMap.put("userInfo", sysUser);

                    userMap.put("memberInfo", memberInfo);

                    cache.setex(token, 60 * 60 * 24, userMap);

                    rd.setData(token);

                } else {
                    rd.setResult(false);
                    rd.setCode("111111");
                    rd.setMsg("密码错误");
                }
            }

        } else if ((type == "phoneCodeLogin" || "phoneCodeLogin".equals(type)) && (verifiction != null) && phone != null) {//验证码登录

            String sysVeri = cache.get("login" + verifiction[0]).toString();//获取redis中的验证码
            if (sysVeri == null) {//验证码过期
                rd.setMsg("请重新获取验证码");
                rd.setCode("111111");
                rd.setResult(false);

            } else if (!sysVeri.equals(verifiction[0])) {//验证码不正确
                rd.setMsg("验证码错误");
                rd.setCode("111111");
                rd.setResult(false);

            } else if (sysVeri.equals(verifiction[0])) {//验证码正确

                //判断用户是否存在
                Record sysUser = Db.findFirst("SELECT * from sys_user  type='7' and where phone = '" + phone[0] + "'");
                if (sysUser == null) {
                    rd.setResult(false);
                    rd.setCode("111111");
                    rd.setMsg("用户不存在");
                } else {
                    rd.setResult(true);
                    rd.setCode("000000");
                    rd.setMsg("登录成功");

                    /*查询会员信息*/

                    String userId = sysUser.getStr("id");

                    Record memberInfo = mobileServices.getMemberByUserIdService(userId);

                    String token = AES.AESEncode(userId);

                    Map<String, Record> userMap = new HashMap<>();

                    userMap.put("userInfo", sysUser);

                    userMap.put("memberInfo", memberInfo);

                    cache.setex(token, 60 * 60 * 24, userMap);

                    rd.setData(token);


                }

            }

        }

        return rd;
    }

    public static String getInvitationNum(){
        List<Object> invitationNumList = Db.query("select invitationNum from yx_member");
        String invNum=UuidUtil.get6UUID();
        Iterator<Object> iterator = invitationNumList.iterator();
        while(iterator.hasNext()){
            if (!invNum.equals(iterator.next()))break;
            invNum=UuidUtil.get6UUID();
        }
        return invNum;
    }
}
